package com.medicine.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

import com.medicine.model.User;
import com.medicine.service.IUserService;

public class OnlineListener implements HttpSessionListener {
	
	private static Logger logger = Logger.getLogger(OnlineListener.class);

	public void sessionCreated(HttpSessionEvent se) {
		try {
			HttpSession session = se.getSession();
			User user=(User) session.getAttribute(CommonConstant.LOGIN_USER);
			System.out.println("================session create user:"+user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void sessionDestroyed(HttpSessionEvent se) {
		User user = null;
		try {
			HttpSession session = se.getSession();
			//ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"spring-mvc.xml"});
			//userService = (IUserService) ac.getBean("userService");
			user=(User) session.getAttribute(CommonConstant.LOGIN_USER);
			if(null != user){
				System.out.println("================session destory user:"+user.getId());
				//修改用户的登陆状态
				//int updateNum = userService.updateByPrimaryKey(user);
				String sql="UPDATE USER SET login_status = 0 WHERE id="+user.getId();
				updateUserLoginStatus(sql);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("==========================userId:"+user.getId()+" session fail,update loginStatus error!");
		}
		
	}
	
	/*private static String url =null;
	
	private String user = null;;
	
	private  String passwd =null;
	
	public static Connection conn = null;  
    public PreparedStatement pst = null; */
    
   
	
	private static void updateUserLoginStatus(String sql){
		Connection conn = null;
		PreparedStatement pst =null;
		try {
			String url = LoadProperty.getValueByKey("db.url");
			String user = LoadProperty.getValueByKey("db.username");
			String passwd = LoadProperty.getValueByKey("db.password");
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, passwd);
			pst = conn.prepareStatement(sql);
			int num = pst.executeUpdate();
		} catch (ClassNotFoundException  e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				pst.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

}
